package io.zim.modules.back.controller;

import io.zim.common.exception.RRException;
import io.zim.common.utils.R;
import io.zim.modules.oss.service.SysOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传接口
 *
 * @author zzh
 * @email 862583291@qq.com
 * @date 2019年1月29日 上午10:40:10
 */
@RestController
@RequestMapping("/back/file")
public class UploadController {
    @Autowired
    private SysOssService sysOssService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String url = null;
        try {
            url = sysOssService.upload(file);
        } catch (Exception e) {
            new RRException(e.getMessage());
        }
        return R.ok().put("url", url);
    }

    /**
     * 通过url删除文件
     */
    @PostMapping("/deleteByUrl")
    public R deleteByUrl(@RequestBody String url){
        if (url.isEmpty()) {
            throw new RRException("删除文件地址不能为空");
        }
        try {
            sysOssService.deleteByUrl(url);
        } catch (Exception e) {
            new RRException(e.getMessage());
        }
        return R.ok();
    }
}
